package cn.bonoon.services.plugins;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.plugins.PlaceService;
import cn.bonoon.entities.PlaceEntity;
import cn.bonoon.entities.PlaceLevel;
import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.support.services.AbstractTreeService;
import cn.bonoon.kernel.util.StringHelper;
@Service("placeServiceImpl")
@Transactional(readOnly = true)
public class PlaceServiceImpl extends AbstractTreeService<PlaceEntity> implements PlaceService{

	@Override
	public List<PlaceEntity> children(long id) {
		return __list(domainClass, "select x from PlaceEntity x where x.deleted=false and x.parent.id=?", id);
	}

	@Override
	public List<PlaceEntity> byLevel(int level) {
		return __list(domainClass, "select x from PlaceEntity x where x.deleted=false and x.level=?", level);
	}

	@Override
	public int placeLevel(Long id) {
		return __single(Integer.class, "select x.level from PlaceEntity x where x.id=?", id).intValue();
	}
	
	private void __parent(PlaceEntity entity){
		PlaceEntity parent = entity.getParent();
		if(parent != null){
			__parent2(parent);
			if(StringHelper.isEmpty(entity.getCode())){
				entity.setCode(parent.getCode());
			}
		}
	}
	
	private void __parent2(PlaceEntity entity){
		PlaceEntity parent = entity.getParent();
		if(parent != null){
			__parent2(parent);
			entity.setFullName(parent.getFullName() + entity.getName());
			entity.setXpath(parent.getXpath() + entity.getId() + "/");
		}else{
			entity.setFullName(entity.getName());
			entity.setXpath(entity.getId() + "/");
		}
		entity.setSize(entity.getChildren().size());
	}
	
	@Override
	protected PlaceEntity __save(OperateEvent event, PlaceEntity entity) throws Exception{
		__parent(entity);
		return super.__save(event, entity);
	}
	
	@Override
	protected PlaceEntity __update(OperateEvent event, PlaceEntity entity)throws Exception {
		__parent(entity);
		entity.setSize(entity.getChildren().size());
		return super.__update(event, entity);
	}
	
	@Override
	public PlaceLevel userLevel(LogonUser user) {
		PlaceLevel level=__first(PlaceLevel.class, "select p.level from PlaceEntity as p where id="+user.getOwnerId());
		return level;
	}
}
